document.addEventListener('DOMContentLoaded', () => {
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');

    // 初始化画布宽高
    const setCanvasSize = () => {
        canvas.width = window.innerWidth * window.devicePixelRatio;
        canvas.height = window.innerHeight * window.devicePixelRatio;
    };

    setCanvasSize();

    // 根据DPR计算字体的大小
    const fontSize = 20 * window.devicePixelRatio;
    ctx.font = `${fontSize}px "Consolas"`;

    // 计算总列数
    const columnCount = Math.floor(canvas.width / fontSize);
    const charIndex = new Array(columnCount).fill(0);

    // 绘制代码雨
    const draw = () => {
        ctx.fillStyle = 'rgba(0,0,0,0.1)';
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        ctx.fillStyle = '#6be445';
        ctx.textBaseline = 'top';

        for (let i = 0; i < columnCount; i++) {
            const text = getRandomChar();
            const x = i * fontSize;
            const y = charIndex[i] * fontSize;
            ctx.fillText(text, x, y);

            if (y > canvas.height && Math.random() > 0.99) {
                charIndex[i] = 0;
            } else {
                charIndex[i]++;
            }
        }
    };

    // 每50毫秒绘制一次
    setInterval(draw, 50);

    // 获取随机字符
    const getRandomChar = () => {
        const str = '0123456789abcdefghijklmnopqrstuvwxyz';
        return str[Math.floor(Math.random() * str.length)];
    };

    // 当窗口大小改变时重新设置画布大小
    window.addEventListener('resize', setCanvasSize);
});
